<template>
	<view class="page-box">
		<!-- user -->
		<view class="centerY pad-left-right-30 pad-top-bottom-60 user-bg">
			<image class="avatar" src="@/static/image/logo.png"></image>
			<view class="columnY betweenX centerY flex-w mar-left-30">
				<view class="color-white">
					<view class="bold font-30">欢迎您，{{userInfo.nickname}}</view>
					<view class="font-28 mar-top-10">余额：{{balanceInfo.amount}}元</view>
				</view>
				<view class="withdraw-box">
					<view @click="hanldeWithdrawal" class="withdraw font-26">提现</view>
					<!-- <view @click="hanldeProcess" class="withdraw font-26">操作指引</view> -->
				</view>
			</view>
		</view>

		<!-- 明细 -->
		<view v-if="info?.enable_receive_rebate == 2"
			class="color-error text-center pad-left-right-30 mar-top-30 font-28">
			您没有参加邀请奖励的活动资格
		</view>
		<!-- <view class="color-error pad-left-right-30 mar-top-30 font-28">
			新用户推广({{info.receive_special_rebate_days}})天内，返利比例为({{info.receive_special_rebate_rate}}),之后返利比例为({{info.receive_rebate_rate}})
		</view> -->
		<view v-else class="pad-left-right-30 mar-top-30">
			<view class="centerY bg-white pad-30 radius30 font-28">
				<view class="flex-w centerXY columnY">
					<view>
						<text class="color-primary bold">{{info.received_total_amount}}</text>
						<text class="mar-left-10">元</text>
					</view>
					<view class="mar-top-10 color-646464">返利金额</view>
				</view>
				<view class="flex-w centerXY columnY">
					<view>
						<text class="color-primary bold">{{info.cid_cnt}}</text>
						<text class="mar-left-10">人</text>
					</view>
					<view class="mar-top-10 color-646464">推广客户</view>
				</view>
			</view>
		</view>

		<view class="pad-left-right-30 mar-top-30">
			<view class="bg-white radius30">
				<up-cell @click="hanldeRebatList" icon="/static/image/my2.png" :border="false" size="large" title="返利明细"
					isLink>
				</up-cell>
				<up-cell @click="hanldeRebatListLog" icon="/static/image/my2.png" :border="false" size="large"
					title="已邀请注册的记录" isLink>
				</up-cell>
				<!-- #ifdef MP-WEIXIN -->
				<button class="custom-button" open-type="share">
					<up-cell icon="/static/image/my2.png" :border="false" size="large" title="我要推广转发" isLink>
					</up-cell>
				</button>
				<!-- #endif -->
				<up-cell @click="hanldeqcCode" icon="/static/image/my2.png" :border="false" size="large" title="专属推广二维码"
					isLink>
				</up-cell>
				<up-cell @click="popupShow = true" icon="/static/image/my2.png" :border="false" size="large"
					title="专属推广海报" isLink>
				</up-cell>
			</view>
		</view>

		<!-- 推广二维码 -->
		<up-popup :show="qcCode" mode="center" @close="close" bgColor="transparent">
			<view class="popup-box pad-30 radius30 bg-white">
				<image style="width:400rpx;height: 400rpx;" :src="path"></image>
				<l-painter class="hide" isCanvasToTempFilePath useCORS :board="qcCodeposter" @success="path = $event" />
			</view>
			<view class="close-box centerXY mar-top-30">
				<image @click="close" class="close-model" src="/static/image/close.png" />
			</view>
		</up-popup>

		<!-- 推广海报 -->
		<up-popup :show="popupShow" mode="center" @close="close" bgColor="transparent">
			<view class="popup-box">
				<image style="width:690rpx;height: 1100rpx;" :src="posterPath"></image>
				<l-painter class="hide" ref="posterRef" isCanvasToTempFilePath useCORS :board="poster"
					@success="posterPath = $event" />
				<view class="mar_top40 btn flex align-center">
					<up-button @click="save" type="primary" shape="circle" color="#FFFFFF"
						:customStyle="{height: '100rpx',background:'#77c0ce'}">
						<text class="color_theme fontS32 font_weight500">下载分享海报</text>
					</up-button>
				</view>
				<view class="close-box centerXY mar-top-30">
					<image @click="close" class="close-model" src="/static/image/close.png" />
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { userRebateApi } from '@/api/index.js'
	import { onShow, onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
	import { getBaseInfo, balanceDetail } from '@/api/index.js'
	import { postMultiGet } from '@/api/currency.js';
	import util from '@/util/share.js'

	const hanldeqcCode = () => {
		if (path.value) {
			qcCode.value = true;
		}
	}

	onLoad(() => {
		util.friends();
	})

	const hanldeProcess = () => {
		uni.navigateTo({
			url: '../process/process'
		})
	}

	const hanldeWithdrawal = () => {
		uni.navigateTo({
			url: '../withdrawal/withdrawal'
		})
	}

	const qcCode = ref(false);
	const popupShow = ref(false);
	const path = ref('');
	const uid = uni.getStorageSync('userId');
	const qcCodeposter = ref()
	const poster = ref();
	const posterPath = ref('');
	const posterRef = ref(null);

	const getPostAllOfGroup = () => {
		postMultiGet({ codes: 'h5_redirect_url,rebate_share_poster' }).then(res => {
			if (res.code == 200) {
				let { h5_redirect_url, rebate_share_poster } = res.data.lists;
				const posterData = JSON.parse(rebate_share_poster);

				// 单独二维码
				qcCodeposter.value = {
					css: {
						width: '400rpx',
						height: '400rpx',
						position: 'relative'
					},
					views: [{
						type: 'qrcode',
						text: `${h5_redirect_url}?ref=wxmini_user_share&uid=${uid}&go=/pages/index/index`,
						css: {
							width: '400rpx',
							height: '400rpx',
							position: 'absolute',
							bottom: '0rpx',
							left: '0rpx'
						}
					}]
				}

				// 海报
				poster.value = {
					css: {
						width: '690rpx',
						height: '1100rpx',
						position: 'relative'
					},
					views: [{
							type: 'image',
							src: posterData.bgurl,
							css: {
								width: '690rpx',
								height: '1100rpx',
								position: 'absolute',
								top: '0rpx',
								left: '0rpx'
							}
						},
						{
							type: 'qrcode',
							text: `${h5_redirect_url}?ref=wxmini_user_share&uid=${uid}&go=/pages/index/index`,
							css: {
								width: '200rpx',
								height: '200rpx',
								position: 'absolute',
								bottom: posterData.draw_qrcode_args[2] + 'rpx',
								left: posterData.draw_qrcode_args[3] + 'rpx'
							}
						}
					]
				}
			}
		})
	}

	// 保存图片到手机
	const save = () => {
		posterRef.value.canvasToTempFilePathSync({
			fileType: 'png',
			pathType: 'url',
			quality: 1,
			success: (res) => {
				// #ifdef H5 
				download_files(posterPath.value, `分享图片`, {
					showMessage: false
				})
				// #endif

				// #ifndef H5
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success: () => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 2000
								});
							},
							fail: (error) => {
								console.log(error);
							}
						});
					},
					fail: (error) => {
						uni.showModal({
							title: '提示',
							content: '需要授权相册权限才能保存图片，请前往设置中开启',
							success(modalRes) {
								if (modalRes.confirm) {
									// 打开设置页
									uni.openSetting()
								}
							}
						})
					}
				})
				// #endif
			},
			fail(err) {
				console.log('???????????', err)
			}
		})
	}

	const download_files = (url, fileName, msgConfig = {}) => {
		const {
			showMessage = true, success = '导出成功！', error = '导出失败！'
		} = msgConfig
		return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest()
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					// 响应成功 并且 响应文件类型不能是html (url不存在的话会下载html文件)
					if (xhr.status === 200 && !xhr.response.type.includes('htm')) {
						xhr.onload = function(e) {
							const blob = xhr.response
							if ('msSaveOrOpenBlob' in navigator) {
								window.navigator.msSaveOrOpenBlob(blob, fileName)
							} else {
								const a = document.createElement('a')
								a.download = fileName
								a.href = URL.createObjectURL(blob)
								a.click()
							}
							showMessage && Message.success(success)
							resolve()
						}
					} else {
						reject()
					}
				}
			}
			xhr.open('GET', url, true)
			xhr.responseType = 'blob'
			xhr.send()
		}).catch(() => { // 错误处理
			showMessage && Message.error(error)
		})
	}

	// 关闭弹窗
	const close = () => {
		popupShow.value = false;
		qcCode.value = false;
	}


	// 分享
	onShareAppMessage(() => {
		return util.onShare({
			path: `/pages/index/index`
		})
	})

	onShareTimeline(() => {
		let uid = "";
		if (uni.getStorageSync('userId')) {
			uid = uni.getStorageSync('userId');
		}
		let imageUrl = uni.getStorageSync('shareCover');
		
		return {
			query: `uid=${uid}&ref=wxmini_user_share`,
			title: "心宇利家政",
			imageUrl: imageUrl
		}
	})

	// 获取分销详情
	const info = ref({});
	const getUserRebateApi = () => {
		userRebateApi().then(res => {
			if (res?.code == 200) {
				info.value = res.data.info;
			}
		})
	}

	// 跳转链接
	const hanldeRebatList = () => {
		uni.navigateTo({
			url: '../rebatList/rebatList'
		})
	}

	const hanldeRebatListLog = () => {
		uni.navigateTo({
			url: '../registerLog/registerLog'
		})
	}

	// 打开海报
	const hanldePoster = () => {

	}

	// 获取用户信息
	const userInfo = ref({});
	const balanceInfo = ref({})
	const getUserInfo = () => {
		getBaseInfo().then(res => {
			if (res?.code == 200) {
				userInfo.value = res.data.info;
				uni.setStorageSync('userId', res.data.info.id);
			}
		})

		balanceDetail().then(res => {
			if (res?.code == 200) {
				balanceInfo.value = res.data.info;
			}
		})
	}

	onShow(() => {
		getUserInfo();
		getUserRebateApi();
		getPostAllOfGroup();
	})
</script>

<style scoped>
	.user-bg {
		background: #77c0ce;
		position: relative;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.withdraw-box {
		position: fixed;
		right: 0rpx;
	}

	.withdraw {
		background: white;
		color: #77c0ce;
		margin: 20rpx 0;
		border-radius: 30rpx 0 0 30rpx;
		padding: 5rpx 20rpx;
	}

	.hide {
		position: absolute;
		left: -200%;
		top: -200%;
	}

	.close-model {
		width: 40rpx;
		height: 40rpx;
	}

	.custom-button {
		background: none;
		/* 取消背景 */
		border: none;
		/* 取消边框 */
		color: inherit;
		/* 继承父元素的文字颜色 */
		font-size: 16px;
		/* 自定义字体大小 */
		padding: 0;
		/* 取消内边距 */
		box-shadow: none;
		text-align: initial;
		outline: none;
	}

	button::after {
		border: none;
	}
</style>